package com.sicheng.lc.周赛.分类.位运算;

/**
 * @author zsc
 * @version 1.0
 * @date 2022/10/10 10:21
 */
public class 最小XOR {
    //https://leetcode.cn/problems/minimize-xor/
    public int minimizeXor(int a, int b) {
        int c1 = cnt(a), c2 = cnt(b);
        if (c1 == c2)
            return a;
        int c = Math.abs(c1 - c2);
        int res = a;
        if (c2 > c1) {
            for (int i = 0; c > 0 && i < 32; i++) {
                if ((a >> i & 1) == 0) {
                    c--;
                    res |= 1 << i;
                }
            }
            return res;
        }

        for (int i = 0; c > 0 && i < 32; i++) {
            if ((a >> i & 1) == 1) {
                c--;
                res ^= 1 << i;
            }
        }
        return res;
    }

    int cnt(int x) {
        int c = 0;
        while (x != 0) {
            x = x & (x - 1);
            c++;
        }
        return c;
    }

    public static void main(String[] args) {
        最小XOR s = new 最小XOR();
        int a = 25, b = 72;
        System.out.println(s.minimizeXor(a, b));
    }
}
